package com.xjscrm.console.service.customer.wwDevice.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.vo.custmoerplan.CustomerPlanRule;
import com.xjscrm.common.vo.newcustmoerplan.NewCustomerPlanRule;
import com.xjscrm.console.common.util.MyExcelUtil;
import com.xjscrm.console.dto.ChatWwDeviceQueryDTO;
import com.xjscrm.console.entity.MerchatChildDeviceRelation;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.group.SheetHeader;
import com.xjscrm.console.param.operatePlan.*;
import com.xjscrm.console.param.user.ExternalUserIdRateSetDto;
import com.xjscrm.console.param.wwDevice.DeviceGroupDto;
import com.xjscrm.console.param.wwDevice.DeviceGroupQuery;
import com.xjscrm.console.param.wwDevice.WwDeviceDto;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import com.xjscrm.console.vo.*;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WwDeviceServiceImpl implements WwDeviceService {

    @Autowired
    private WwDeviceMapper wwDeviceServiceMapper;

    @Autowired
    private OperatePlanDeviceMapper operatePlanDeviceMapper;

    @Autowired
    private DeviceGroupMapper deviceGroupMapper;

    @Autowired
    private DeviceGroupRelationMapper deviceGroupRelationMapper;

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private OperatePlanMapper operatePlanMapper;

    @Autowired
    private MerchatChildDeviceRelationMapper childDeviceRelationMapper;
    @Autowired
    private WwGroupMemberMapper wwGroupMemberMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MerchatChildDeviceRelationMapper merchatChildDeviceRelationMapper;

    @Autowired
    private TaskTagAutoDeviceMapper taskTagAutoDeviceMapper;

    @Autowired
    private AutoTagPlanServiceMapper autoTagPlanServiceMapper;

    @Autowired
    private FaqReplyDeviceMapper faqReplyDeviceMapper;

    @Autowired
    private FaqReplyMapper faqReplyMapper;

    @Autowired
    private GroupPullConfigDeviceMapper groupPullConfigDeviceMapper;

    @Autowired
    private GroupPullConfigMapper groupPullConfigMapper;

    @Autowired
    private GroupWelcomeDeviceMapper groupWelcomeDeviceMapper;

    @Autowired
    private GroupWelcomeMapper groupWelcomeMapper;

    @Override
    public MyPageInfo<WwDeviceVo> getWwDevice(WwDeviceQuery wwDeviceQuery) {
        if (wwDeviceQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        //查询参数有分组，拿到该组内的机器人ID列表
        if (wwDeviceQuery.getGroupId() != null && wwDeviceQuery.getGroupId() != 0) {
            if (wwDeviceQuery.getGroupId() == 1) {
                //获取未分组的机器人
                List<WwDeviceVo> wwDeviceList = wwDeviceServiceMapper.getWwDeviceList(wwDeviceQuery);
                List<Long> allDeviceUniqueId = new ArrayList<>();
                wwDeviceList.stream().forEach(it -> allDeviceUniqueId.add(it.getId()));
                List<Long> allCollect = allDeviceUniqueId.stream().distinct().collect(Collectors.toList());
                DeviceGroupRelationQuery deviceGroupRelationQuery = new DeviceGroupRelationQuery();
                deviceGroupRelationQuery.setMerId(wwDeviceQuery.getMerId());
                List<DeviceGroupRelation> deviceGroupRelationList = deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);
                List<Long> existDeviceUniqueId = new ArrayList<>();
                deviceGroupRelationList.forEach(it -> existDeviceUniqueId.add(it.getDeviceUniqueId()));
                List<Long> existCollect = existDeviceUniqueId.stream().distinct().collect(Collectors.toList());
                List<Long> absentCollect = allCollect.stream().filter(it -> !existCollect.contains(it)).collect(Collectors.toList());
                if (absentCollect != null && !absentCollect.isEmpty()) {
                    wwDeviceQuery.setDeviceUniqueIds(absentCollect);
                } else {
                    return new MyPageInfo<WwDeviceVo>(null);
                }

            } else {
                DeviceGroupRelationQuery deviceGroupRelationQuery = new DeviceGroupRelationQuery();
                deviceGroupRelationQuery.setMerId(wwDeviceQuery.getMerId());
                deviceGroupRelationQuery.setGroupId(wwDeviceQuery.getGroupId());
                List<DeviceGroupRelation> deviceGroupRelationList = deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);

                List<Long> deviceUniqueIds = new ArrayList<>();
                if (deviceGroupRelationList != null && !deviceGroupRelationList.isEmpty()) {
                    for (DeviceGroupRelation deviceGroupRelation : deviceGroupRelationList) {
                        deviceUniqueIds.add(deviceGroupRelation.getDeviceUniqueId());
                    }
                }

                if (deviceUniqueIds != null && !deviceUniqueIds.isEmpty()) {
                    wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
                } else {
                    return new MyPageInfo<WwDeviceVo>(null);
                }
            }
        }

        if (wwDeviceQuery.getLoginStatus() != null) {
            List<WwDevice> wwDeviceList = wwDeviceServiceMapper.selectByMerId(wwDeviceQuery.getMerId());
            if (wwDeviceList == null || wwDeviceList.isEmpty()) {
                return new MyPageInfo<WwDeviceVo>(null);
            }

            List<Long> onlineDeviceUniqueIds = new ArrayList<>();
            List<Long> offlineDeviceUniqueIds = new ArrayList<>();
            for (WwDevice wwDevice : wwDeviceList) {
                Integer lastHeatBeatTime = (Integer) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WW_DEVICE_LAST_HEAT_BEAT_TIME.getKey(), wwDevice.getDeviceId()));
                if (lastHeatBeatTime != null && (DateUtil.getTime() - lastHeatBeatTime) <= 300) {
                    onlineDeviceUniqueIds.add(wwDevice.getId());
                } else {
                    offlineDeviceUniqueIds.add(wwDevice.getId());
                }
            }

            if (wwDeviceQuery.getLoginStatus() == 1) {
                if (onlineDeviceUniqueIds.isEmpty()) {
                    return new MyPageInfo<WwDeviceVo>(null);
                }
                wwDeviceQuery.setLoginStatusDeviceUniqueIds(onlineDeviceUniqueIds);
            }
            if (wwDeviceQuery.getLoginStatus() == 2) {
                if (offlineDeviceUniqueIds.isEmpty()) {
                    return new MyPageInfo<WwDeviceVo>(null);
                }
                wwDeviceQuery.setLoginStatusDeviceUniqueIds(offlineDeviceUniqueIds);
            }
        }

        //如果是子账号，只能查看自己账号所管理的 机器人
        if (wwDeviceQuery.getOperatorType() != null && wwDeviceQuery.getOperatorType() == 1) {
            if (wwDeviceQuery.getChildId() == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID为空");
            }
            List<MerchatChildDeviceRelation> merchatChildDeviceRelationList = merchatChildDeviceRelationMapper.selectByStaffId(wwDeviceQuery.getMerId(), wwDeviceQuery.getChildId());
            if (merchatChildDeviceRelationList == null || merchatChildDeviceRelationList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = merchatChildDeviceRelationList.stream().map(MerchatChildDeviceRelation::getRobotId).distinct().collect(Collectors.toList());
            wwDeviceQuery.setChildOwnDeviceUniqueIds(deviceUniqueIds);
        }

        String orderBy = OrderByUtil.getOrderBy(wwDeviceQuery.getOrderByField(), wwDeviceQuery.isAsc());
        PageHelper.startPage(wwDeviceQuery.getCurrent(), wwDeviceQuery.getSize(), orderBy);
        List<WwDeviceVo> wwDeviceList = wwDeviceServiceMapper.getWwDeviceList(wwDeviceQuery);

        if (wwDeviceList == null || wwDeviceList.isEmpty()) {
            return new MyPageInfo<WwDeviceVo>(null);
        }

        for (WwDeviceVo wwDeviceVo : wwDeviceList) {
            try {
                getExpansionInfo(wwDeviceVo);
                //获取机器人所在群数
                Integer num = wwGroupMemberMapper.getCountByWxid(wwDeviceVo.getDeviceId(), wwDeviceVo.getMerId());
                wwDeviceVo.setInGroupNum(num);

                //获取在线状态
                Integer lastHeatBeatTime = (Integer) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WW_DEVICE_LAST_HEAT_BEAT_TIME.getKey(), wwDeviceVo.getDeviceId()));
                if (lastHeatBeatTime != null && (DateUtil.getTime() - lastHeatBeatTime) <= 300) {
                    wwDeviceVo.setLoginStatus(1);
                } else {
                    wwDeviceVo.setLoginStatus(0);
                }

                //获取会员外部账号id频率
                try {
                    String externalUseridRateKey = String.format(RedisCacheKeyEnum.DEIVCE_EXTERNAL_USERID_RATE.getKey(), wwDeviceVo.getId());
                    Integer externalUseridRateObject = (Integer) redisTemplate.opsForValue().get(externalUseridRateKey);
                    wwDeviceVo.setExternalUseridRate(externalUseridRateObject);
                } catch (Exception e) {

                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        MyPageInfo<WwDeviceVo> pageInfo = new MyPageInfo<>(wwDeviceList);
        return pageInfo;
    }


    @Override
    public Object getWwDevicedetail(WwDeviceDto wwDeviceDto) {
        if (wwDeviceDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (wwDeviceDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwDevice wwDevice = wwDeviceServiceMapper.getById(wwDeviceDto.getId(), wwDeviceDto.getMerId());
        WwDeviceVo wwDeviceVo = new WwDeviceVo();
        if (wwDevice != null) {
            BeanUtil.copyProperties(wwDevice, wwDeviceVo);
            getExpansionInfo(wwDeviceVo);

            Integer lastHeatBeatTime = (Integer) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WW_DEVICE_LAST_HEAT_BEAT_TIME.getKey(), wwDeviceVo.getDeviceId()));
            if (lastHeatBeatTime != null && (DateUtil.getTime() - lastHeatBeatTime) <= 300) {
                wwDeviceVo.setLoginStatus(1);
            } else {
                wwDeviceVo.setLoginStatus(0);
            }
        }

        return wwDeviceVo;
    }

    private void getExpansionInfo(WwDeviceVo wwDeviceVo) {
        //查询是否被其他新客方案使用
        OperatePlanDeviceQuery operatePlanDeviceQuery = new OperatePlanDeviceQuery();
        operatePlanDeviceQuery.setMerId(wwDeviceVo.getMerId());
        operatePlanDeviceQuery.setPlanType(0);
        operatePlanDeviceQuery.setDeviceUniqueId(wwDeviceVo.getId());
        List<OperatePlanDeviceVo> operatePlanDeviceList = operatePlanDeviceMapper.getOperatePlanDeviceList(operatePlanDeviceQuery);
        if (operatePlanDeviceList == null || operatePlanDeviceList.isEmpty()) {
            wwDeviceVo.setUseNewCustomerPlan(0);
        } else {
            wwDeviceVo.setUseNewCustomerPlan(1);
        }

        //查询是否被运营方案默认规则使用
        OperatePlanDeviceQuery operatePlanDeviceQuery1 = new OperatePlanDeviceQuery();
        operatePlanDeviceQuery1.setMerId(wwDeviceVo.getMerId());
        operatePlanDeviceQuery1.setPlanType(1);
        operatePlanDeviceQuery1.setRuleType(1);
        operatePlanDeviceQuery1.setDeviceUniqueId(wwDeviceVo.getId());
        List<OperatePlanDeviceVo> operatePlanDeviceList1 = operatePlanDeviceMapper.getOperatePlanDeviceList(operatePlanDeviceQuery1);
        if (operatePlanDeviceList1 == null || operatePlanDeviceList1.isEmpty()) {
            wwDeviceVo.setDefaultCustomerPlanRule(0);
        } else {
            wwDeviceVo.setDefaultCustomerPlanRule(1);
        }

        //查询是否被运营方案条件规则使用
        OperatePlanDeviceQuery operatePlanDeviceQuery2 = new OperatePlanDeviceQuery();
        operatePlanDeviceQuery2.setMerId(wwDeviceVo.getMerId());
        operatePlanDeviceQuery2.setPlanType(1);
        operatePlanDeviceQuery2.setRuleType(2);
        operatePlanDeviceQuery2.setDeviceUniqueId(wwDeviceVo.getId());
        List<OperatePlanDeviceVo> operatePlanDeviceList2 = operatePlanDeviceMapper.getOperatePlanDeviceList(operatePlanDeviceQuery2);
        if (operatePlanDeviceList2 == null || operatePlanDeviceList2.isEmpty()) {
            wwDeviceVo.setConditionCustomerPlanRule(0);
        } else {
            wwDeviceVo.setConditionCustomerPlanRule(1);
        }

        //获取该机器人的客户数
        int customerNum = wwCustomerMapper.countCustomerByDeviceUniqueId(wwDeviceVo.getId(), wwDeviceVo.getMerId());
        wwDeviceVo.setCustomerNum(customerNum);

        //获取分组
        DeviceGroupRelationQuery deviceGroupRelationQuery = new DeviceGroupRelationQuery();
        deviceGroupRelationQuery.setMerId(wwDeviceVo.getMerId());
        deviceGroupRelationQuery.setDeviceUniqueId(wwDeviceVo.getId());
        List<DeviceGroupRelation> deviceGroupRelationList = deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);
        List<String> groupNames = new ArrayList<>();
        if (deviceGroupRelationList != null && !deviceGroupRelationList.isEmpty()) {
            for (DeviceGroupRelation deviceGroupRelation : deviceGroupRelationList) {
                DeviceGroup deviceGroup = deviceGroupMapper.getDeviceGroupById(deviceGroupRelation.getGroupId(), deviceGroupRelation.getMerId());
                groupNames.add(deviceGroup.getGroupName());
            }
        }
        if (groupNames != null && !groupNames.isEmpty()) {
            wwDeviceVo.setGroupNames(groupNames);
        }
    }


    @Override
    public Object getOperatePlan(WwDeviceDto wwDeviceDto) {
        if (wwDeviceDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (wwDeviceDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (wwDeviceDto.getPlanType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        OperatePlanDeviceQuery operatePlanDeviceQuery = new OperatePlanDeviceQuery();
        operatePlanDeviceQuery.setDeviceUniqueId(wwDeviceDto.getId());
        operatePlanDeviceQuery.setMerId(wwDeviceDto.getMerId());
        operatePlanDeviceQuery.setPlanType(wwDeviceDto.getPlanType());
        List<OperatePlanDeviceVo> operatePlanDeviceList = operatePlanDeviceMapper.getOperatePlanDeviceList(operatePlanDeviceQuery);
        List<OperatePlanVo> operatePlanVoList = new ArrayList<>();
        if (operatePlanDeviceList != null && !operatePlanDeviceList.isEmpty()) {
            for (OperatePlanDeviceVo operatePlanDeviceVo : operatePlanDeviceList) {
                OperatePlanVo operatePlanVo = new OperatePlanVo();
                OperatePlan operatePlan = operatePlanMapper.getOperatePlanById(operatePlanDeviceVo.getPlanId(), operatePlanDeviceVo.getMerId());
                BeanUtil.copyProperties(operatePlan, operatePlanVo);
                if (operatePlanVo.getPlanType() == 0) {
                    operatePlanVo.setNewCustomerPlanRule(JSONObject.parseObject(operatePlan.getPlanRule(), NewCustomerPlanRule.class));
                }
                if (operatePlanVo.getPlanType() == 1) {
                    operatePlanVo.setCustomerPlanRule(JSONObject.parseObject(operatePlan.getPlanRule(), CustomerPlanRule.class));
                }
                operatePlanVoList.add(operatePlanVo);
            }
        }
        return operatePlanVoList;
    }


    @Override
    public Object getTaskTagAuto(WwDeviceDto wwDeviceDto) {
        if (wwDeviceDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (wwDeviceDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        List<TaskTagAutoVo> taskTagAutoList = new ArrayList<>();

        //查询选择了部分机器人的自动打标签方案
        TaskTagAutoDeviceQuery taskTagAutoDeviceQuery = new TaskTagAutoDeviceQuery();
        taskTagAutoDeviceQuery.setMerId(wwDeviceDto.getMerId());
        taskTagAutoDeviceQuery.setDeviceUniqueId(wwDeviceDto.getId());
        List<TaskTagAutoDevice> taskTagAutoDeviceList = taskTagAutoDeviceMapper.taskTagAutoDeviceList(taskTagAutoDeviceQuery);

        if (taskTagAutoDeviceList != null && !taskTagAutoDeviceList.isEmpty()) {
            for (TaskTagAutoDevice taskTagAutoDevice : taskTagAutoDeviceList) {
                try {
                    TaskTagAuto taskTagAuto = autoTagPlanServiceMapper.getById(taskTagAutoDevice.getTaskId(), taskTagAutoDevice.getMerId());
                    if (taskTagAuto != null) {
                        TaskTagAutoVo taskTagAutoVo = new TaskTagAutoVo();
                        BeanUtil.copyProperties(taskTagAuto, taskTagAutoVo, "paraRule", "eventRule");
                        taskTagAutoList.add(taskTagAutoVo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        //获取选择了所有机器人的自动打标签方案
        TaskTagAutoQuery taskTagAutoQuery = new TaskTagAutoQuery();
        taskTagAutoQuery.setMerId(wwDeviceDto.getMerId());
        taskTagAutoQuery.setTagType(1);
        taskTagAutoQuery.setEnterpriseType(0);
        List<TaskTagAutoVo> taskTagAutoVoList = autoTagPlanServiceMapper.getTaskTagAutoList(taskTagAutoQuery);

        //合并所有方案
        if (taskTagAutoVoList != null && !taskTagAutoVoList.isEmpty()) {
            taskTagAutoList.addAll(taskTagAutoVoList);
        }

        //根据方案ID去重
        List<TaskTagAutoVo> finalTaskTagAutoList = taskTagAutoList.stream()
                .collect(Collectors.toMap(TaskTagAutoVo::getId, it -> it, (existing, replacement) -> existing))
                .values()
                .stream()
                .collect(Collectors.toList());

        return finalTaskTagAutoList;
    }


    @Override
    public Object getFaqReply(WwDeviceDto wwDeviceDto) {

        if (wwDeviceDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (wwDeviceDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        //通过智能应答关联的机器人获取智能应答方案
        List<FaqReplyVo> faqReplyVoList = new ArrayList<>();

        FaqReplyDeviceQuery faqReplyDeviceQuery = new FaqReplyDeviceQuery();
        faqReplyDeviceQuery.setMerId(wwDeviceDto.getMerId());
        faqReplyDeviceQuery.setDeviceUniqueId(wwDeviceDto.getId());
        List<FaqReplyDeviceVo> faqReplyDeviceVoList = faqReplyDeviceMapper.getFaqReplyDeviceList(faqReplyDeviceQuery);

        if (faqReplyDeviceVoList != null && !faqReplyDeviceVoList.isEmpty()) {
            for (FaqReplyDeviceVo faqReplyDeviceVo : faqReplyDeviceVoList) {
                try {
                    FaqReply faqReply = faqReplyMapper.getById(faqReplyDeviceVo.getTaskId(), faqReplyDeviceVo.getMerId());
                    if (faqReply != null) {
                        FaqReplyVo faqReplyVo = new FaqReplyVo();
                        BeanUtil.copyProperties(faqReply, faqReplyVo);
                        faqReplyVoList.add(faqReplyVo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        //根据方案ID去重
        List<FaqReplyVo> finalFaqReplyVoList = faqReplyVoList.stream()
                .collect(Collectors.toMap(FaqReplyVo::getId, it -> it, (existing, replacement) -> existing))
                .values()
                .stream()
                .collect(Collectors.toList());

        return finalFaqReplyVoList;
    }


    @Override
    public Object getGroupPull(WwDeviceDto wwDeviceDto) {

        if (wwDeviceDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (wwDeviceDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (wwDeviceDto.getGroupPullType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        List<GroupPullVo> groupPullVoList = new ArrayList<>();

        GroupPullDeviceQuery groupPullDeviceQuery = new GroupPullDeviceQuery();
        groupPullDeviceQuery.setMerId(wwDeviceDto.getMerId());
        groupPullDeviceQuery.setDeviceUniqueId(wwDeviceDto.getId());
        groupPullDeviceQuery.setType(wwDeviceDto.getGroupPullType());
        List<GroupPullConfigDeviceVo> groupPullConfigDeviceVoList = groupPullConfigDeviceMapper.getDelPlanDeviceList(groupPullDeviceQuery);

        if (groupPullConfigDeviceVoList != null && !groupPullConfigDeviceVoList.isEmpty()) {
            for (GroupPullConfigDeviceVo groupPullConfigDeviceVo : groupPullConfigDeviceVoList) {
                try {
                    GroupPullConfig groupPullConfig = groupPullConfigMapper.getById(groupPullConfigDeviceVo.getPlanId(), groupPullConfigDeviceVo.getMerId());
                    if (groupPullConfig != null) {
                        GroupPullVo groupPullVo = new GroupPullVo();
                        BeanUtil.copyProperties(groupPullConfig, groupPullVo);
                        groupPullVoList.add(groupPullVo);
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        //根据方案ID去重
        List<GroupPullVo> finalGroupPullVoList = groupPullVoList.stream()
                .collect(Collectors.toMap(GroupPullVo::getId, it -> it, (existing, replacement) -> existing))
                .values()
                .stream()
                .collect(Collectors.toList());

        return finalGroupPullVoList;
    }


    @Override
    public Object getGroupWelcome(WwDeviceDto wwDeviceDto) {

        if (wwDeviceDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (wwDeviceDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        List<GroupWelcomeVo> groupWelcomeVoList = new ArrayList<>();

        GroupWelcomeDeviceQuery groupWelcomeDeviceQuery = new GroupWelcomeDeviceQuery();
        groupWelcomeDeviceQuery.setMerId(wwDeviceDto.getMerId());
        groupWelcomeDeviceQuery.setDeviceUniqueId(wwDeviceDto.getId());
        List<GroupWelcomeDeviceVo> groupWelcomeDeviceVoList = groupWelcomeDeviceMapper.getGroupWelcomeDeviceList(groupWelcomeDeviceQuery);

        if (groupWelcomeDeviceVoList != null && !groupWelcomeDeviceVoList.isEmpty()) {
            for (GroupWelcomeDeviceVo groupWelcomeDeviceVo : groupWelcomeDeviceVoList) {
                try {
                    GroupWelcome groupWelcome = groupWelcomeMapper.getById(groupWelcomeDeviceVo.getPlanId(), groupWelcomeDeviceVo.getMerId());
                    if (groupWelcome != null) {
                        GroupWelcomeVo groupWelcomeVo = new GroupWelcomeVo();
                        BeanUtil.copyProperties(groupWelcome, groupWelcomeVo);
                        groupWelcomeVoList.add(groupWelcomeVo);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        //根据方案ID去重
        List<GroupWelcomeVo> finalGroupWelcomeVoList = groupWelcomeVoList.stream()
                .collect(Collectors.toMap(GroupWelcomeVo::getId, it -> it, (existing, replacement) -> existing))
                .values()
                .stream()
                .collect(Collectors.toList());

        return finalGroupWelcomeVoList;
    }

    @Override
    public Object getDeviceGroup(DeviceGroupDto deviceGroupDto) {
        if (deviceGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        ArrayList<Map> mapArrayList = new ArrayList<>();
        //获取所有的机器人
        WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
        wwDeviceQuery.setMerId(deviceGroupDto.getMerId());

        //如果是子账号，只能查看自己账号所管理的 机器人
        if (deviceGroupDto.getOperatorType() != null && deviceGroupDto.getOperatorType() == 1) {
            if (deviceGroupDto.getChildId() == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID为空");
            }
            wwDeviceQuery.setChildId(deviceGroupDto.getChildId());
            List<MerchatChildDeviceRelation> merchatChildDeviceRelationList = merchatChildDeviceRelationMapper.selectByStaffId(wwDeviceQuery.getMerId(), wwDeviceQuery.getChildId());
            if (merchatChildDeviceRelationList == null || merchatChildDeviceRelationList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = merchatChildDeviceRelationList.stream().map(MerchatChildDeviceRelation::getRobotId).distinct().collect(Collectors.toList());
            wwDeviceQuery.setChildOwnDeviceUniqueIds(deviceUniqueIds);
        }

        List<WwDeviceVo> wwDeviceList = wwDeviceServiceMapper.getWwDeviceList(wwDeviceQuery);
        HashMap<String, Object> allDeviceMap = new HashMap<>();
        allDeviceMap.put("id", 0);
        allDeviceMap.put("name", "全部分组");
        allDeviceMap.put("number", wwDeviceList.size());
        mapArrayList.add(allDeviceMap);

        //获取未分组的机器人
        List<Long> allDeviceUniqueId = new ArrayList<>();
        wwDeviceList.stream().forEach(it -> allDeviceUniqueId.add(it.getId()));
        List<Long> allCollect = allDeviceUniqueId.stream().distinct().collect(Collectors.toList());
        DeviceGroupRelationQuery deviceGroupRelationQuery = new DeviceGroupRelationQuery();
        deviceGroupRelationQuery.setMerId(deviceGroupDto.getMerId());
        if (deviceGroupDto.getOperatorType() == 1) {
            deviceGroupRelationQuery.setDeviceUniqueIds(wwDeviceQuery.getChildOwnDeviceUniqueIds());
        }
        List<DeviceGroupRelation> deviceGroupRelationList = deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);
        List<Long> existDeviceUniqueId = new ArrayList<>();
        deviceGroupRelationList.forEach(it -> existDeviceUniqueId.add(it.getDeviceUniqueId()));
        List<Long> existCollect = existDeviceUniqueId.stream().distinct().collect(Collectors.toList());
        List<Long> absentCollect = allCollect.stream().filter(it -> !existCollect.contains(it)).collect(Collectors.toList());
        HashMap<String, Object> absentDeviceMap = new HashMap<>();
        absentDeviceMap.put("id", 1);
        absentDeviceMap.put("name", "未分组");
        absentDeviceMap.put("number", absentCollect.size());
        mapArrayList.add(absentDeviceMap);

        DeviceGroupQuery deviceGroupQuery = new DeviceGroupQuery();
        deviceGroupQuery.setMerId(deviceGroupDto.getMerId());
        List<DeviceGroupVo> deviceGroupList = deviceGroupMapper.getDeviceGroupList(deviceGroupQuery);
        for (DeviceGroupVo deviceGroupVo : deviceGroupList) {
            try {
                HashMap<String, Object> map = new HashMap<>();
                int deviceNum = 0;

                if (deviceGroupDto.getOperatorType() == 1) {
                    deviceNum = deviceGroupRelationMapper.countDeviceGroupRelationByGroupIdAndDeviceIds(deviceGroupVo.getId(), deviceGroupVo.getMerId(), wwDeviceQuery.getChildOwnDeviceUniqueIds());
                } else {
                    deviceNum = deviceGroupRelationMapper.countDeviceGroupRelationByGroupId(deviceGroupVo.getId(), deviceGroupVo.getMerId());
                }
                map.put("id", deviceGroupVo.getId());
                map.put("name", deviceGroupVo.getGroupName());
                map.put("number", deviceNum);
                mapArrayList.add(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mapArrayList;
    }

    @Override
    public Object onlineWwDeviceNum(BaseDto baseDto) {
        if (baseDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        Integer onlineWwDeviceNum = 0;
        List<WwDevice> wwDeviceList = wwDeviceServiceMapper.selectByMerId(baseDto.getMerId());
        if (wwDeviceList == null && wwDeviceList.isEmpty()) {
            return onlineWwDeviceNum;
        }

        for (WwDevice wwDevice : wwDeviceList) {
            Integer lastHeatBeatTime = (Integer) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WW_DEVICE_LAST_HEAT_BEAT_TIME.getKey(), wwDevice.getDeviceId()));
            if (lastHeatBeatTime != null && (DateUtil.getTime() - lastHeatBeatTime) <= 300) {
                onlineWwDeviceNum++;
            }
        }
        return onlineWwDeviceNum;
    }

    @Override
    public Object getDeviceGroupDropdwon(BaseDto baseDto) {
        if (baseDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        DeviceGroupQuery deviceGroupQuery = new DeviceGroupQuery();
        deviceGroupQuery.setMerId(baseDto.getMerId());
        List<DeviceGroupVo> deviceGroupList = deviceGroupMapper.getDeviceGroupList(deviceGroupQuery);
        ArrayList<Map> DropdwonList = new ArrayList<>();
        if (deviceGroupList != null || !deviceGroupList.isEmpty()) {
            for (DeviceGroupVo deviceGroup : deviceGroupList) {
                try {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("label", deviceGroup.getGroupName());
                    map.put("value", deviceGroup.getId());
                    DropdwonList.add(map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return DropdwonList;
    }

    @Override
    public Object getDeviceDropDwon(BaseDto baseDto) {
        if (baseDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();

        //如果是子账号，只能查看自己账号所管理的 机器人
        if (baseDto.getOperatorType() != null && baseDto.getOperatorType() == 1) {
            if (baseDto.getChildId() == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID为空");
            }
            List<MerchatChildDeviceRelation> merchatChildDeviceRelationList = merchatChildDeviceRelationMapper.selectByStaffId(baseDto.getMerId(), baseDto.getChildId());
            if (merchatChildDeviceRelationList == null || merchatChildDeviceRelationList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = merchatChildDeviceRelationList.stream().map(MerchatChildDeviceRelation::getRobotId).distinct().collect(Collectors.toList());
            wwDeviceQuery.setChildOwnDeviceUniqueIds(deviceUniqueIds);
        }

        wwDeviceQuery.setMerId(baseDto.getMerId());
        List<WwDeviceVo> wwDeviceList = wwDeviceServiceMapper.getWwDeviceList(wwDeviceQuery);
        ArrayList<Map> DropdwonList = new ArrayList<>();
        if (wwDeviceList != null || !wwDeviceList.isEmpty()) {
            for (WwDeviceVo wwDeviceVo : wwDeviceList) {
                try {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("label", wwDeviceVo.getDeviceName());
                    map.put("value", wwDeviceVo.getId());
                    map.put("corpId", wwDeviceVo.getCorpId());
                    DropdwonList.add(map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return DropdwonList;
    }


    @Override
    public void addDeviceGroup(DeviceGroupDto deviceGroupDto) {
        if (deviceGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (StringUtils.isBlank(deviceGroupDto.getGroupName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        DeviceGroup deviceGroup = new DeviceGroup();
        BeanUtil.copyProperties(deviceGroupDto, deviceGroup);
        deviceGroup.setDeviceType(0);
        deviceGroupMapper.addDeviceGroup(deviceGroup);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleDeviceGroup(DeviceGroupDto deviceGroupDto) {
        if (deviceGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (deviceGroupDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        //查询出机器人和分组的关系,并删除
        DeviceGroupRelationQuery deviceGroupRelationQuery = new DeviceGroupRelationQuery();
        deviceGroupRelationQuery.setMerId(deviceGroupDto.getMerId());
        deviceGroupRelationQuery.setGroupId(deviceGroupDto.getId());
        List<DeviceGroupRelation> deviceGroupRelationList = deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);
        if (deviceGroupRelationList != null && !deviceGroupRelationList.isEmpty()) {
            deviceGroupRelationList.forEach(it -> {
                deviceGroupRelationMapper.deleDeviceGroupRelation(it.getId(), it.getMerId());
            });
        }
        //删除机器人组
        deviceGroupMapper.deleDeviceGroup(deviceGroupDto.getId(), deviceGroupDto.getMerId());
    }


    @Override
    public void deleDeviceGroupRelation(DeviceGroupDto deviceGroupDto) {
        if (deviceGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (deviceGroupDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (deviceGroupDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        DeviceGroupRelationQuery deviceGroupRelationQuery = new DeviceGroupRelationQuery();
        deviceGroupRelationQuery.setMerId(deviceGroupDto.getMerId());
        deviceGroupRelationQuery.setDeviceUniqueId(deviceGroupDto.getDeviceUniqueId());
        deviceGroupRelationQuery.setGroupId(deviceGroupDto.getId());
        List<DeviceGroupRelation> deviceGroupRelationList = deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);

        if (deviceGroupRelationList != null && !deviceGroupRelationList.isEmpty()) {
            for (DeviceGroupRelation deviceGroupRelation : deviceGroupRelationList) {
                deviceGroupRelationMapper.deleDeviceGroupRelation(deviceGroupRelation.getId(), deviceGroupRelation.getMerId());
            }
        }
    }


    @Override
    public void updateDeviceGroup(DeviceGroupDto deviceGroupDto) {
        if (deviceGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (deviceGroupDto.getNewGroupName() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (deviceGroupDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        DeviceGroup deviceGroup = deviceGroupMapper.getDeviceGroupById(deviceGroupDto.getId(), deviceGroupDto.getMerId());
        if (deviceGroup != null) {
            deviceGroup.setGroupName(deviceGroupDto.getNewGroupName());
            deviceGroupMapper.updateDeviceGroup(deviceGroup);

        }

    }

    @Override
    public void moveDeviceGroup(DeviceGroupDto deviceGroupDto) {
        if (deviceGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (deviceGroupDto.getNewGroupId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (deviceGroupDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (deviceGroupDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        //新增机器人与分组关系
        try {
            DeviceGroupRelation deviceGroupRelation = new DeviceGroupRelation();
            deviceGroupRelation.setMerId(deviceGroupDto.getMerId());
            deviceGroupRelation.setDeviceUniqueId(deviceGroupDto.getDeviceUniqueId());
            deviceGroupRelation.setGroupId(deviceGroupDto.getNewGroupId());
            deviceGroupRelationMapper.addDeviceGroupRelation(deviceGroupRelation);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不能加入同一组");
        }

        //删除原分组
        if (deviceGroupDto.getType() == 0 && deviceGroupDto.getId() != null) {
            //查询出当前机器人分组关系
            DeviceGroupRelationQuery deviceGroupRelationQuery = new DeviceGroupRelationQuery();
            deviceGroupRelationQuery.setMerId(deviceGroupDto.getMerId());
            deviceGroupRelationQuery.setDeviceUniqueId(deviceGroupDto.getDeviceUniqueId());
            deviceGroupRelationQuery.setGroupId(deviceGroupDto.getId());
            List<DeviceGroupRelation> deviceGroupRelationList = deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);
            if (deviceGroupRelationList != null && !deviceGroupRelationList.isEmpty()) {
                deviceGroupRelationList.forEach(it -> {
                    deviceGroupRelationMapper.deleDeviceGroupRelation(it.getId(), it.getMerId());
                });
            }
        }


    }

    @Override
    public List<WwDevice> listByCondition(WwDeviceQuery wwDeviceQuery) {

        WwDeviceQuery copyQuery = new WwDeviceQuery();
        BeanUtils.copyProperties(wwDeviceQuery, copyQuery);
        copyQuery.setLoginStatus(1);

        return wwDeviceServiceMapper.selectList(wwDeviceQuery);
    }


    @Override
    @Async("taskExecutor")
    public void batchMoveDeviceGroupAll(DeviceGroupDto deviceGroupDto) {
        if (deviceGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (deviceGroupDto.getWwDeviceQuery() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        WwDeviceQuery wwDeviceQuery = deviceGroupDto.getWwDeviceQuery();
        Long idStart = 0L;
        wwDeviceQuery.setMerId(deviceGroupDto.getMerId());
        wwDeviceQuery.setAsc(true);
        wwDeviceQuery.setCurrent(1);
        wwDeviceQuery.setSize(100);
        wwDeviceQuery.setOrderByField("id");
        wwDeviceQuery.setIdStart(idStart);
        List<WwDeviceVo> wwDeviceVoList = getWwDevice(wwDeviceQuery).getRecords();
        while (wwDeviceVoList != null && !wwDeviceVoList.isEmpty()) {
            for (WwDeviceVo wwDeviceVo : wwDeviceVoList) {
                try {
                    if (wwDeviceVo.getId().longValue() > idStart.longValue()) {
                        idStart = wwDeviceVo.getId();
                    }
                    deviceGroupDto.setDeviceUniqueId(wwDeviceVo.getId());
                    moveDeviceGroup(deviceGroupDto);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            wwDeviceQuery.setIdStart(idStart);
            wwDeviceVoList = getWwDevice(wwDeviceQuery).getRecords();
        }
    }

    @Override
    @Async("taskExecutor")
    public void batchDeleDeviceGroupAll(DeviceGroupDto deviceGroupDto) {
        if (deviceGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (deviceGroupDto.getWwDeviceQuery() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        WwDeviceQuery wwDeviceQuery = deviceGroupDto.getWwDeviceQuery();
        Long idStart = 0L;
        wwDeviceQuery.setMerId(deviceGroupDto.getMerId());
        wwDeviceQuery.setAsc(true);
        wwDeviceQuery.setCurrent(1);
        wwDeviceQuery.setSize(100);
        wwDeviceQuery.setOrderByField("id");
        wwDeviceQuery.setIdStart(idStart);
        List<WwDeviceVo> wwDeviceVoList = getWwDevice(wwDeviceQuery).getRecords();
        while (wwDeviceVoList != null && !wwDeviceVoList.isEmpty()) {
            for (WwDeviceVo wwDeviceVo : wwDeviceVoList) {
                try {
                    if (wwDeviceVo.getId().longValue() > idStart.longValue()) {
                        idStart = wwDeviceVo.getId();
                    }
                    deviceGroupDto.setDeviceUniqueId(wwDeviceVo.getId());
                    deleDeviceGroupRelation(deviceGroupDto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            wwDeviceQuery.setIdStart(idStart);
            wwDeviceVoList = getWwDevice(wwDeviceQuery).getRecords();
        }
    }

    @Override
    public WwDevice getByDeviceId(WwDeviceQuery wwDeviceQuery) {

        return this.wwDeviceServiceMapper.selectByDeviceId(wwDeviceQuery.getMerId(), wwDeviceQuery.getDeviceId());
    }

    @Override
    public WwDevice getByDeviceId(@MerId Long merId, String deviceId) {
        return this.wwDeviceServiceMapper.selectByDeviceId(merId, deviceId);
    }

    @Override
    public WwDevice getById(@MerId Long merId, Long id) {
        return this.wwDeviceServiceMapper.selectById(merId, id);
    }

    @Override
    public List<WwDevice> getByIds(@MerId Long merId, List<Long> deviceUniqueIds) {
        return wwDeviceServiceMapper.selectByIds(merId, deviceUniqueIds);
    }

    @Override
    public List<WwDevice> listByMerId(@MerId Long merId) {

        return wwDeviceServiceMapper.selectByMerId(merId);
    }

    @Override
    public boolean update(WwDevice wwDevice) {
        wwDeviceServiceMapper.updateWwDevice(wwDevice);
        return true;
    }

    @Override
    public Object pageWithChat(LoginVO login, ChatWwDeviceQueryDTO query) {

        boolean isMaster = Objects.equals(login.getId(), login.getMerId());

        WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
        wwDeviceQuery.setMerId(login.getMerId());
        wwDeviceQuery.setOpenChat(query.getOpenChat());
        wwDeviceQuery.setKeyword(query.getKeyword());
        if (!isMaster) {
            List<MerchatChildDeviceRelation> deviceRelationList = childDeviceRelationMapper.selectByStaffId(login.getMerId(), login.getId());
            if (ObjectUtils.isEmpty(deviceRelationList)) {
                return new MyPageInfo<>(Lists.newArrayList());
            }
            List<Long> deviceUniqueIds = deviceRelationList.stream().map(MerchatChildDeviceRelation::getRobotId).distinct().collect(Collectors.toList());
            wwDeviceQuery.setDeviceUniqueIds(deviceUniqueIds);
        }

        PageHelper.startPage(query.getCurrent(), query.getSize());
        List<WwDeviceVo> wwDeviceList = wwDeviceServiceMapper.getWwDeviceList(wwDeviceQuery);

        return new MyPageInfo<>(wwDeviceList);
    }

    @Override
    public void exportDevice(WwDeviceQuery wwDeviceQuery, HttpServletResponse response) {
        if (wwDeviceQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (wwDeviceQuery.getFieldList() == null && wwDeviceQuery.getFieldList().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        wwDeviceQuery.setCurrent(1);
        wwDeviceQuery.setSize(10000);
        MyPageInfo<WwDeviceVo> wwDeviceVoMyPageInfo = getWwDevice(wwDeviceQuery);
        if (wwDeviceVoMyPageInfo.getRecords() != null && !wwDeviceVoMyPageInfo.getRecords().isEmpty()) {
            List<WwDeviceVo> records = wwDeviceVoMyPageInfo.getRecords();
            records.forEach(it -> {
                it.setGroupNamesDesc();
                it.setOpenChatDesc();
            });

            List<String> FieldsList = wwDeviceQuery.getFieldList().stream().map(SheetHeader::getDataIndex).distinct().collect(Collectors.toList());

            Map<String, String> replacements = new HashMap<>();
            replacements.put("openChat", "openChatDesc");
            replacements.put("groupNames", "groupNamesDesc");
            List<String> Fields = FieldsList.stream()
                    .map(str -> replacements.getOrDefault(str, str))
                    .collect(Collectors.toList());

            List<String> titles = wwDeviceQuery.getFieldList().stream().map(SheetHeader::getTitle).distinct().collect(Collectors.toList());

            // 使用Stream筛选匹配的字段
            List<Object> matchedObjects = records.stream()
                    .map(obj -> {
                        Map<String, Object> matchedFields = new HashMap<>();
                        Fields.forEach(field -> {
                            try {
                                Field objField = obj.getClass().getDeclaredField(field);
                                objField.setAccessible(true);
                                matchedFields.put(field, objField.get(obj));
                            } catch (NoSuchFieldException | IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        });
                        return matchedFields;
                    })
                    .filter(fieldsMap -> fieldsMap.size() == Fields.size())
                    .collect(Collectors.toList());

            try {
                MyExcelUtil.exportExcel(response, titles, matchedObjects, Fields);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }


    public void setExternalUseridRate(ExternalUserIdRateSetDto externalUserIdRateSetDto) {

        List<Long> deviceUniqueIds = externalUserIdRateSetDto.getDeviceUniqueIds();

        Integer externalUseridRate = externalUserIdRateSetDto.getExternalUseridRate();

        if (deviceUniqueIds == null || externalUseridRate == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        for (int i = 0; i < deviceUniqueIds.size(); i++) {
            Long deviceUniqueId = deviceUniqueIds.get(i);
            String externalUseridRateKey = String.format(RedisCacheKeyEnum.DEIVCE_EXTERNAL_USERID_RATE.getKey(), deviceUniqueId);
            redisTemplate.opsForValue().set(externalUseridRateKey, externalUseridRate);
        }

    }


}
